package com.vf.s.mvc.sys.controller;

import java.util.LinkedList;
import java.util.List;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.vf.core.controller.BaseController;
import com.vf.core.util.MD5Util;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.scene.Scene;
import com.vf.s.common.model.sys.SysOrg;
import com.vf.s.common.model.sys.SysRole;
import com.vf.s.common.model.sys.SysUser;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;
import com.vf.s.mvc.sys.service.UserService;

public class UserController extends BaseController {

	protected final Log LOG = Log.getLog(getClass());

	@Inject
	private UserService srv;

	public void index() {
		List<Scene> scenes=Scene.dao.find("SELECT * FROM "+Scene.TABLE_NAME);
		this.set("scenes",scenes);
		render("list.html");
	}

	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String key = getPara("key");
		String sqlExceptSelect = " FROM " + SysUser.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.USERNAME LIKE '%" + keyword + "%' OR   O.NAME '%" + keyword + "%' ) ";
		}
		if (!StrKit.isBlank(key)) {
			sqlExceptSelect += " AND O.ID IN (SELECT USERID FROM SYS_USER_ROLE WHERE ROLEID IN (SELECT ID FROM SYS_ROLE WHERE CODE='"+key+"') ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.CREATETIME asc ";
		Page<SysUser> page = SysUser.dao.paginate(pageNumber, pageSize, "select *,(select name from sys_org where id=o.orgid ) as orgName ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	/***
	 * 保存
	 */
	public void save() {
		SysUser sysUser = getModel(SysUser.class);
		if (StrKit.notBlank(sysUser.getID())) {
			SysUser namesysUser = SysUser.dao.findFirst(
					"SELECT * FROM " + SysUser.TABLE_NAME + " WHERE USERNAME=? AND ID!=?", sysUser.getUSERNAME(),
					sysUser.getID());
			if (namesysUser != null) {
				renderError("名称已存在！");
				return;
			}
			if (sysUser.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			SysUser namesysUser = SysUser.dao.findFirst("SELECT * FROM " + SysUser.TABLE_NAME + " WHERE USERNAME=?",
					sysUser.getUSERNAME());
			if (namesysUser != null) {
				renderError("名称已存在！");
				return;
			}
			sysUser.setID(UuidUtil.getUUID());
			PasswordService svc = new DefaultPasswordService();
			sysUser.setPASSWORD(svc.encryptPassword(MD5Util.get(sysUser.getUSERNAME())));
			if (sysUser.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}

	/***
	 * 删除
	 * 
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		SysUser sysUser = SysUser.dao.findById(id);
		if (sysUser != null) {
			if (sysUser.delete()) {
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
    public void updatePwd() {
    	String oldPsw=this.getPara("oldPsw");
    	String newPsw=this.getPara("newPsw");
    	String rePsw=this.getPara("rePsw");
    	
    	if(StrKit.isBlank(newPsw) ||  StrKit.isBlank(rePsw) ||  StrKit.isBlank(oldPsw)) {
    		this.renderError("新旧密码不可以为空！");
    		return;
    	}
    	if(!StrKit.equals(rePsw, newPsw)) {
    		this.renderError("新密码2次输入不一致！");
    		return;
    	}
		SimpleUser sysAccount = ShiroKit.getLoginUser();
		if(sysAccount!=null) {
			SysUser user=SysUser.dao.findById(sysAccount.getId());
			String password = String.valueOf(oldPsw);
			PasswordService svc = new DefaultPasswordService();
			if (svc.passwordsMatch(MD5Util.get(password), user.getPASSWORD())) {
				user.setPASSWORD(svc.encryptPassword(MD5Util.get(newPsw)));
				if(user.update()) {
					renderSuccess("密码修改成功！");
				}else {
					this.renderError("密码修改失败！");
				}
			} else {
				this.renderError("原始密码有误！");
			}
		}else {
			this.setAttr("message", "会话过期 !");
			this.redirect("/login");
		}
    }
    
    /*****************************************用户数据授权******************************************************/
	public void authOrgTree() {
    	String userId=this.getPara("userId");
		List<SysOrg> list=SysOrg.dao.find("select t.id,t.parentId as pId, t.name, "
				+ " (CASE  WHEN (SELECT count(id) as count from sys_user_org where ORGID=t.id and USERID=? )>0 THEN true ELSE  false END ) as checked   "
				+ " from "+SysOrg.TABLE_NAME+"  t  ORDER BY t.sort asc",userId);
		this.renderJson(list);
	}
	
	@Before(Tx.class)
	public void saveAuthOrg() {
		String userId = getPara("userId");
		String authIds = getPara("authIds");
		SysUser user = SysUser.dao.findById(userId);
		if (user != null) {
			List<String>  arr = JSONObject.parseArray(authIds, String.class);  
			List<String> sqlList = new LinkedList<String>();
			if (arr != null && arr.size() > 0) {
				sqlList.add("DELETE  FROM SYS_USER_ORG WHERE USERID='" + userId + "' ");
				if (SysRole.excuteSql(sqlList)) {
					sqlList.clear();
					for (String orgId : arr) {
						sqlList.add("INSERT INTO SYS_USER_ORG (ID,USERID,ORGID) VALUES('" + UuidUtil.getUUID() + "','"
								+userId  + "','" +orgId  + "')");
					}
					if (SysRole.excuteSql(sqlList)) {
						renderSuccess("授权成功！");
					} else {
						renderError("授权操作失败!");
					}
				} else {
					renderError("授权操作失败!");
				}
			} else {
				sqlList.add("DELETE  FROM SYS_USER_ORG WHERE USERID='" + userId + "' ");
				if (SysRole.excuteSql(sqlList)) {
					renderSuccess("取消授权成功！");
				}else {
					renderError("取消授权失败!");
				}
			}
		} else {
			renderError("授权用户不存在,请刷新后再试!");
		}
	}
	
	@Before(Tx.class)
	public void saveAuthRole() {
		String userId = getPara("userId");
		String authIds = getPara("authIds");
		SysUser user = SysUser.dao.findById(userId);
		if (user != null) {
			List<String>  arr = JSONObject.parseArray(authIds, String.class);  
			List<String> sqlList = new LinkedList<String>();
			if (arr != null && arr.size() > 0) {
				sqlList.add("DELETE  FROM SYS_USER_ROLE WHERE USERID='" + userId + "' ");
				if (SysRole.excuteSql(sqlList)) {
					sqlList.clear();
					for (String roleId : arr) {
						sqlList.add("INSERT INTO SYS_USER_ROLE (ID,USERID,ROLEID) VALUES('" + UuidUtil.getUUID() + "','"
								+userId  + "','" +roleId  + "')");
					}
					if (SysRole.excuteSql(sqlList)) {
						renderSuccess("授权成功！");
					} else {
						renderError("授权操作失败!");
					}
				} else {
					renderError("授权操作失败!");
				}
			} else {
				sqlList.add("DELETE  FROM SYS_USER_ROLE WHERE USERID='" + userId + "' ");
				if (SysRole.excuteSql(sqlList)) {
					renderSuccess("取消授权成功！");
				}else {
					renderError("取消授权失败!");
				}
			}
		} else {
			renderError("授权用户不存在,请刷新后再试!");
		}
	}
    
	public void authListRole() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		Page<SysRole> page = SysRole.dao.paginate(pageNumber, pageSize, "SELECT T.*,"
				+ " (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM SYS_USER_ROLE where ROLEID=T.ID and USERID='"+this.getPara("userId")+"' )>0 THEN true ELSE false END )  AS LAY_CHECKED  ", " FROM SYS_ROLE  T  ORDER BY T.SORT ASC");
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	

}
